using System;
using System.Collections.Generic;
using Client.Base;
using UnityEngine;
namespace Client.Hotfix
{


    [SSM(SSMWeight.OperationModule)]
    public class OperationModule : IAwake, IDestroy
    {
        public IModule CurModule { get; private set; }
        private Dictionary<int, IModule> moduleCache = null;
        public void Awake(params object[] args)
        {
            this.Log("[Module] - OperationModule is running...");

            var targetAttribute = typeof(CModuleAttribute);

            // 获取所有带有 CModuleAttribute 特性的类型
            var typesWithAttribute = AssemblyHelper.GetAttribute4Assembly<CModuleAttribute>("CHotFix");

            if (typesWithAttribute != null && typesWithAttribute.Count > 0)
            {
                moduleCache = new Dictionary<int, IModule>();

                foreach (var item in typesWithAttribute)
                {
                    Type moduleType = item.Type;
                    int hashcode = moduleType.GetHashCode();
                    // 检查是否已存在相同类型的模块
                    if (moduleCache.ContainsKey(hashcode))
                    {
                        continue;
                    }

                    // 创建实例
                    var moduleInstance = Activator.CreateInstance(moduleType) as IModule;

                    if (moduleInstance == null)
                    {
                        continue;
                    }

                    // 添加到缓存
                    moduleCache.Add(hashcode, moduleInstance);

                }
            }
            else
            {
                Debug.Log("[Module] - 未找到任何带有 CModuleAttribute 的类型");
            }

        }

        public void Destroy()
        {

        }

        public void EnterModule<T>() where T : IModule
        {
            int hashcode = typeof(T).GetHashCode();
            if (!moduleCache.ContainsKey(hashcode)) return;
            var m = moduleCache[hashcode];
            if (CurModule == m) return;
            CurModule?.Exit();
            CurModule = m;
            CurModule.Enter();
        }
    }
}


